
const express = require("express")
const fs = require("fs")
const router = express.Router()
const multer =require('multer')
const sqlQuery = require("../../mysql/index.cjs")
const path = require("path")
const { log } = require("console")
let img = '../../images'
// 设置上传的目录文件夹
let url = path.join(__dirname,img)

let storage = multer.diskStorage({
  destination :function(req,file,cb){
    // console.log('111',req.body);
    // // console.log(req);
    // let url = noteURL(req.body.id)
    // console.log(url);
    cb(null,url)
  },
  filename : function(req,file,cb){
    let timeStamp = new Date().getTime()
    // 上传速度过快导致时间戳一致
    let i = Math.floor(Math.random()*10)
    console.log(timeStamp,i);
    let a = 0
    a++
    // console.log(file);
    cb(null,timeStamp+i + '.' + file.originalname.split(".")[1])
  }
})


const upload = multer({storage:storage})


function noteURL(id){
  if(id){
    // 判断 文件夹是否存在
    let flg = fs.existsSync(path.join(__dirname,`${img}/${id}`))
    if(!flg){
      // 如果不存在就创建
      fs.mkdirSync(path.join(__dirname,`${img}/${id}`))
      fs.mkdirSync(path.join(__dirname,`${img}/${id}/notes`))
      let noteURL = path.join(__dirname,`${img}/${id}/notes/`)
      return noteURL
    }else{
      let noteURL = path.join(__dirname,`${img}/${id}/notes/`)
      return noteURL
    }
  }
}



router.post("/uploader", upload.any(), function(req, res, next) {
  // 获取传过来的参数创建文件夹 保存图片
  let body = req.body
  // 图片暂存路径
  let url = noteURL(body.id)
  // 保存数据库的url 数组
  let noteURLs = []
  // 获取传递过来的文件循环
  for (let index = 0; index < req.files.length; index++) {
    // 获取图片暂存路径
    let path = req.files[index].path
    // 获取图片名字
    let img = path.substring( path.lastIndexOf("\\")+1)
    // 添加到数组
    noteURLs.push(`${body.id}/notes/${img}`)
    let imgUrl =url+ img
    try {
      fs.renameSync(path,imgUrl)
    } catch (error) {
      
    }
  }
  // 获取表单传递的参数
  let title = body.title
  let user_id = body.id
  let content = body.content
  let urls = JSON.stringify(noteURLs)
  //  准备sql语句
  let sql = `insert into note(user_id,url,title,content) values(${user_id},'${urls}',"${title}","${content}")`
  sqlQuery(sql,msg=>{
    if(msg.affectedRows){
      res.send({
        status : 100,
        msg : "上传成功"
      })
    }
  })
});







module.exports =router